
const { ipcMain,BrowserWindow } = require('electron') 
const WinState  = require('electron-win-state').default

const path = require('path')



const saveas = require('./saveas')


// width:60px; height:30px; background-color:cornflowerblue; border-radius:5px; text-align:center; line-height:30px;

const cssText =`width:80px; height:30px; background-color:cornflowerblue; border-radius:5px; text-align:center; line-height:30px; position:fixed; bottom:50px; right:20px; z-index:1000; color:#fff; cursor:default;`


const js = `
    const div = document.createElement('div')
    div.id = 'redit-button'
    div.innerHTML = '关闭窗口'
    div.style.cssText = '${cssText}'

    div.addEventListener('click',() => {
        window.myApi.close()
    })

    document.body.appendChild(div)
`



let win = null


ipcMain.handle('on-open-event',(e,url) => {

    const winState = new WinState({
        defaultHeight:800,
        defaultWidth:1200,
        electronStoreOptions:{
            name:"window-state-open"
        }
    })

    win = new BrowserWindow({
        ...winState.winOptions,
        // width:1200,
        // heigt:800,
        show:false,
        webPreferences:{
            preload:path.resolve(__dirname,'../preload/open.js')
        }
    })


    win.loadURL(url)



    win.on('ready-to-show',() => {
        win.show()
    })

    winState.manage(win)

    //打开开发者工具
    win.webContents.openDevTools()

    win.webContents.executeJavaScript(js).catch(() => {

    })


    //监听右键点击事件,args可以接收到一些参数
    //例如在图片上面点击的时候，可以抓到图片的路由
    win.webContents.on('context-menu',(e,args) => {
        saveas(args.srcURL)
    })

    
})


ipcMain.handle('on-close-event',(e) => {
    win.close()
})